import {
  base64src
} from '../../libs/base64src.js'
import api from '../../api/api'

var app = getApp()
var WxParse = require('../../wxParse/wxParse.js')
import {
  productId
} from '../../api/conf'
import {
  towishlist
} from '../../api/conf'
import {
  cartCount
} from '../../api/conf'
import {
  goodstocart
} from '../../api/conf'
import {
  goodstocheckout
} from '../../api/conf'
import {
  iscollect
} from '../../api/conf'
import {
  weixinopenlogin
} from '../../api/conf'
import {
  weixinopenphonenumber
} from '../../api/conf'
import {
  getgoodsattr
} from '../../api/conf'
import {
  getgoodsspec
} from '../../api/conf'
import {
  topic
} from '../../api/conf'
import {
  getUnlimited
} from '../../api/conf'
import {
  gettemplates
} from '../../api/conf'

import {
  minitemgoodsqty
} from '../../api/conf'
var bmap = require('../../libs/bmap-wx.min.js');
Page({
  data: {
    model: {},
    cartNum: 0,
    proNum: 10,
    miniNum: 0,
    proId: 0,
    iscollet: 0,
    Address: null,
    showAttr: false,
    attrList: [],
    attrprice: '',
    attrqty: '',
    IsPreSelected: 0,
    attrId: 0,
    islogin: false,
    empowerShow: false,
    agentsinfo: '',
    code: '',
    userinfo: '',
    newprice: '',
    isShow: true,
    isprice: false,
    productArr: [],
    tablesArr: [],
    isSelect: [],
    isSelectIndex: [],
    isSelectValue: '',
    contnum: [],
    spec: [],
    wenhou: '',
    allprice: '',
    showService: false,
    servc: [],
    isCanDraw: false,
    qrCodeBase64: '',
    templates: '',
  },
  onLoad: function(options) {
    this.getWeather();
    let scene = decodeURIComponent(options.scene);
    if (scene) {
      let arr = scene.split('&');
      for (let item of arr) {
        let item2 = item.split('=')
        options[item2[0]] = item2[1]
      }
    }

    var that = this
    if (options.code) {
      wx.setStorageSync('code', options.code)
    }
    that.setData({
      proId: options.id
    })
    that.getProductid(options.id)
    this.getgoodsspec(options.id)
    if (!wx.getStorageSync('phone')) {
      this.setData({
        islogin: true
      })
    }

    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) {
            }
          })
        } else {
          that.setData({
            empowerShow: true
          })
        }
      }
    })



  },
  onReady: function() {
  },
  onShow: function() {
    api.get(gettemplates, {}).then((res) => {
      if (res.Data) {

        var templatesData = {};
        switch (res.Data.Default) {
          case 1:
            templatesData.bg = res.Data.Picture1Url;
            break;
          case 2:
            templatesData.bg = res.Data.Picture2Url;
            break;
          case 3:
            templatesData.bg = res.Data.Picture3Url;
            break;
        }

        templatesData.text = res.Data.Text1;
        templatesData.altText = res.Data.AltText1;
        templatesData.textcolor = res.Data.SubText1;
        templatesData.ext = res.Data.Ext1;
        templatesData.Default = res.Data.Default;
        templatesData.Enabled = res.Data.Enabled;
        var date = new Date();
        var that = this;
        if (date.getHours() >= 5 && date.getHours() < 9) {
          templatesData.wenhou = res.Data.TianQiId1Url;
        }
        if (date.getHours() >= 9 && date.getHours() < 12) {
          templatesData.wenhou = res.Data.TianQiId2Url;
        }
        if (date.getHours() >= 11 && date.getHours() < 13) {
          // templatesData.wenhou = res.Data.TianQiId3Url;
        }
        if (date.getHours() >= 12 && date.getHours() < 18) {
          templatesData.wenhou = res.Data.TianQiId4Url;
        }
        if (date.getHours() >= 18 && date.getHours() < 22) {
          templatesData.wenhou = res.Data.TianQiId5Url;
        }
        if (date.getHours() >= 22 || date.getHours() < 2) {
          templatesData.wenhou = res.Data.TianQiId6Url;
        }
        if (date.getHours() >= 2 && date.getHours() < 5) {
          templatesData.wenhou = res.Data.TianQiId7Url;
        }

        this.setData({
          templates: templatesData
        })
      }
    })
    api.get(minitemgoodsqty, {}).then((res) => {
      this.setData({
        miniNum: res.Data
      })

    })
    if (wx.getStorageSync('guid')) {
      this.getCartNum()
    }
    this.getgoodsattr()
    this.getService()
  },
  closeService: function() {
    this.setData({
      showService: false
    })
  },
  getgoodsspec: function(id) {
    var that = this
    api.get(getgoodsspec, {
      pId: id
    }).then(res => {
      that.setData({
        spec: res.Data
      })
    })
  },
  service: function() {
    this.setData({
      showService: true
    })
  },
  getService: function() {
    var that = this
    api.get(topic, {
      systemName: 'service'
    }).then(res => {
      var service = res.Data.Body;
      WxParse.wxParse('service', 'html', service, that, 5);
    })
  },
  contactCallback: function(e) {
    var path = e.detail.path,
      query = e.detail.query,
      params = '';
    if (path) {
      for (var key in query) {
        params = key + '=' + query[key] + '&';
      }
      params = params.slice(0, params.length - 1);
      wx.navigateTo({
        url: path + '?' + params
      })
    }
  },
  getProductid: function(id) {
    var that = this
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    api.get(productId, {
      id: id
    }).then(res => {

      if (res.Data.AttrValueList.length) {
        that.getstring(res)
      }
      let servc = ''
      if (res.Data.IconTip != "") {
        servc = res.Data.IconTip.trim().split(/\s+/)
      }
      that.setData({
        model: res.Data,
        servc: servc,
        attrprice: res.Data.Price,
        attrqty: res.Data.StockQuantity
      })
      var proNum = this.data.proNum

      let str = this.data.model.Price
      str = str.replace(/,/gi, "");
      let prices = parseFloat((str).substr(1))
      var allprice = proNum * prices

      that.setData({
        allprice: allprice.toFixed(2)
      })
      var serviceTip = res.Data.ServiceTip;
      WxParse.wxParse('serviceTip', 'html', serviceTip, that, 5);
      var article = res.Data.Full;
      WxParse.wxParse('article', 'html', article, that, 5);
      wx.hideLoading()
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none'
      })
    })
  },
  //提交收藏
  postTowishlist: function() {
    wx.showNavigationBarLoading()
    api.post(towishlist, {
      PId: this.data.proId,
      Qty: 1
    }).then(res => {
      wx.hideNavigationBarLoading()
      if (res.Code == 200) {
        wx.showToast({
          title: '收藏成功'
        })
      }
    }).catch(err => {
      wx.hideNavigationBarLoading()
      wx.showToast({
        title: '收藏失败',
        icon: 'none'
      })
    })
  },
  addCart: function() {
    var that = this
    if (this.data.showAttr) {
      if ((!this.data.isSelectValue || this.data.isSelectValue == '') && this.data.productArr.attrs.length) {
        wx.showToast({
          title: '请选择规格',
          icon: 'none'
        })
        return
      }
      var uQty = this.data.miniNum > 0 ? this.data.miniNum : this.data.userinfo.Quantity;
      if (this.data.proNum < uQty) {
        wx.showToast({
          title: '该商品数量不能小于' + uQty,
          icon: "none"
        })
        return
      }
      api.post(goodstocart, {
        PId: this.data.proId,
        Qty: this.data.proNum,
        AttrValue: JSON.stringify(this.data.isSelect)
      }).then(res => {
        that.onShow()
        wx.showToast({
          title: '成功加入购物车',
        })
      }).catch(err => {
        wx.showToast({
          title: err.Content,
          icon: 'none'
        })
      })
    } else {
      this.setData({
        showAttr: true
      })
    }
  },
  proInt: function(e) {
    var proNum = e.detail.value

    var uQty = this.data.miniNum > 0 ? this.data.miniNum : this.data.userinfo.Quantity;
    if (e.detail.value <= uQty) {
      wx.showToast({
        title: '数量不能小于' + uQty,
        icon: 'none'
      })
      let updata = this.data.proNum
      this.setData({
        [updata]: 10
      })
    }
    let str = this.data.model.Price
    str = str.replace(/,/gi, "");
    let prices = parseFloat((str).substr(1))
    var allprice = proNum * prices

    this.setData({
      allprice: allprice.toFixed(2),
      proNum: proNum
    })
  },
  proAdd: function() {
    var that = this
    // if (this.data.proNum == 99) {
    //   return
    // }
    if (this.data.proNum >= this.data.isSelectValue.qty) {
      return
    }
    var proNum = this.data.proNum
    proNum++;
    let str = this.data.model.Price
    str = str.replace(/,/gi, "");
    let prices = parseFloat((str).substr(1))
    var allprice = proNum * prices

    this.setData({
      allprice: allprice.toFixed(2),
      proNum: proNum
    })

  },
  proCre: function() {
    var uQty = this.data.miniNum > 0 ? this.data.miniNum : this.data.userinfo.Quantity;
    if (this.data.proNum <= uQty) {
      wx.showToast({
        title: '该商品数量不能小于' + uQty,
        icon: "none"
      })
      return
    }
    var proNum = this.data.proNum
    proNum--;
    let str = this.data.model.Price
    str = str.replace(/,/gi, "");
    let prices = parseFloat((str).substr(1))
    var allprice = proNum * prices

    this.setData({
      allprice: allprice.toFixed(2),
      proNum: proNum
    })
  },
  closeAttr: function() {
    this.setData({
      showAttr: false
    })
  },
  buyBtn: function() {
    if (this.data.showAttr) {
      if ((!this.data.isSelectValue || this.data.isSelectValue == '') && this.data.productArr.attrs.length) {
        wx.showToast({
          title: '请选择规格',
          icon: 'none'
        })
        return
      }
      var uQty = this.data.miniNum > 0 ? this.data.miniNum : this.data.userinfo.Quantity;
      if (this.data.proNum < uQty) {
        wx.showToast({
          title: '该商品数量不能小于' + uQty,
          icon: "none"
        })
        return
      }
      api.post(goodstocheckout, {
        PId: this.data.proId,
        Qty: this.data.proNum,
        AttrValue: JSON.stringify(this.data.isSelect)
      }).then(res => {
        if (res.Code == 200) {
          wx.navigateTo({
            url: '/pages/checkout/checkout',
          })
        }
        wx.hideNavigationBarLoading()
      }).catch(err => {
        wx.hideNavigationBarLoading()
        wx.showToast({
          title: err.Content,
          icon: 'none'
        })
      })
    } else {
      this.setData({
        showAttr: true
      })
    }
  },
  onShareAppMessage: function() {
    let title = this.data.model.Name
    let id = this.data.model.Id
    return {
      title: title,
      path: '/pages/detail/detail?id=' + id + '&code=' + wx.getStorageSync('code'),
    }
  },
  //确定是否收藏
  iscollect: function(id) {
    var that = this
    api.post(iscollect, {
      pid: id
    }).then(res => {
      that.setData({
        iscollet: res.Data
      })
    })
  },
  goHome: function() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  getAdres: function(options) {
    if (options.adres) {
      var timer = setInterval(function() {
        if (app.globalData.location.length) {
          clearInterval(timer)
          for (let i = 0; i < app.globalData.location.length; i++) {
            if (options.adres == app.globalData.location[i].adres.Id) {
              app.globalData.currentAdress = app.globalData.location[i].adres
            }
          }
        }
      }, 100)
    } else {
      this.setData({
        Address: app.globalData.currentAdress
      })
    }
  },
  switchAttr: function(e) {
    var that = this
    let index = e.target.dataset.index
    this.setData({
      IsPreSelected: e.target.dataset.index,
      attrprice: that.data.attrList[index].Price,
      attrqty: that.data.attrList[index].Qty,
      attrId: that.data.attrList[index].Id
    })
  },
  //过滤规格文字格式
  getstring: function(res) {
    let arr = []
    let obj = {}
    let text = ''
    let mhwz = null
    let khwz = null
    let str = ''
    for (let i = 0; i < res.Data.AttrValueList.length; i++) {
      text = res.Data.AttrValueList[i].AttributesXml
      mhwz = text.indexOf(':')
      if (khwz = text.indexOf('[') == -1) {
        str = text.substring(mhwz + 2)
      } else {
        khwz = text.indexOf('[')
        str = text.substring(mhwz + 2, khwz)
      }
      obj = {
        AttributesXml: str,
        Id: res.Data.AttrValueList[i].Id,
        Price: res.Data.AttrValueList[i].Price,
        ProductId: res.Data.AttrValueList[i].ProductId,
        Qty: res.Data.AttrValueList[i].Qty,
        Sku: res.Data.AttrValueList[i].Sku
      }
      arr.push(obj)
    }
    this.setData({
      model: res.Data,
      attrList: arr,
      attrprice: arr[0].Price,
      attrqty: arr[0].Qty,
      attrId: arr[0].Id
    })
  },
  getCartNum: function() {
    var that = this
    api.get(cartCount, {}).then(res => {
      that.setData({
        cartNum: res.Data
      })
      let num = ''
      if (res.Data == 0) {
        num = ''
      } else {
        num = res.Data
      }
      // wx.setTabBarBadge({
      //   index: 2,
      //   text: num
      // })
    })
  },
  getPhoneNumber(e) {
    var that = this
    wx.login({
      success(res) {
        if (res.code) {
          api.get(weixinopenphonenumber, {
            code: res.code,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv
          }).then(res => {
            if (res.Code == 200) {
              wx.setStorageSync('phone', res.Data.phone)
              that.setData({
                islogin: false
              })
              wx.showToast({
                title: '获取手机号成功',
              })
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      fail(err) {
        wx.showToast({
          title: '登录超时',
          icon: 'none'
        })
      }
    })
  },
  bindGetUserInfo: function(e) {
    var that = this
    var guid = null
    if (wx.getStorageSync('guid')) {
      guid = wx.getStorageSync('guid')
    } else {
      guid = null
    }
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function(res) {
              wx.setStorageSync('nickName', res.userInfo.nickName)
              wx.showLoading({
                title: '登录中',
                mask: true
              })
              api.get(weixinopenlogin, {
                code: app.globalData.code,
                guid: guid,
                encryptedData: res.encryptedData,
                iv: res.iv,
                state: that.data.code
              }).then(res => {
                if (res.Code == 200) {
                  wx.setStorageSync('guid', res.Data.guid)
                  wx.setStorageSync('token', res.Data.token)
                  wx.setStorageSync('openId', res.Data.openId)
                  wx.showTabBar({})
                  that.setData({
                    empowerShow: false
                  })
                  wx.hideLoading()
                }
              })
            }
          })
        }
      }
    })
  },
  getgoodsattr: function() {
    var that = this
    api.get(getgoodsattr, {
      pId: this.data.proId
    }).then(res => {
      for (let i in res.Data.attrs) {
        for (let j in res.Data.attrs[i].attrValArr) {
          res.Data.attrs[i].attrValArr[j].isShow = true
        }
      }
      that.setData({
        productArr: res.Data
      })
      that.initAttr()
    })
  },
  newSwitchAttr: function(e) {
    let isSelect = this.data.isSelect
    let attrs = this.data.productArr.attrs
    let index = e.currentTarget.dataset.index
    let indx = e.currentTarget.dataset.indx
    let value = e.currentTarget.dataset.name
    if (isSelect[index] != value) {
      let change = 'isSelect[' + index + ']'
      let change2 = 'isSelectIndex[' + index + ']'
      this.setData({
        [change]: value,
        [change2]: indx
      })
    } else {
      let change = 'isSelect[' + index + ']'
      let change2 = 'isSelectIndex[' + index + ']'
      this.setData({
        [change]: '',
        [change2]: -1
      })
    }
    this.setData({
      proNum: 10
    })
    this.checkAttr()
  },
  checkAttr: function() {
    let attrs = this.data.productArr.attrs
    let result = []
    for (let i in attrs) {
      result[i] = this.data.isSelect[i] ? this.data.isSelect[i] : '';
    }
    for (let i in attrs) {
      let last = result[i];
      for (let k in attrs[i].attrValArr) {
        result[i] = attrs[i].attrValArr[k].value;
        attrs[i].attrValArr[k].isShow = this.isMay(result);
      }
      result[i] = last;
    }
    let cbval = this.cbValue(result)
    this.setData({
      productArr: this.data.productArr,
      isSelectValue: cbval
    })
  },
  isMay: function(result) {
    for (var i in result) {
      if (result[i] == '') {
        return true;
      }
    }
    return this.data.tablesArr[result].qty == 0 ? false : true;
  },
  cbValue: function(result) {
    for (var i in result) {
      if (result[i] == '') {
        return false;
      }
    }
    return this.data.tablesArr[result]
  },
  //修改数据结构格式，改成键值对的方式，以方便和选中之后的值进行匹配
  initAttr: function() {
    this.setData({
      tablesArr: this.data.productArr.tables
    })
    let tablesArr = this.data.tablesArr
    let arr = []
    let obj = {}
    var newsArr = {}
    for (let i in tablesArr) {
      obj = tablesArr[i].info
      arr.push(obj)
    }
    for (let j in tablesArr) {
      let arrs = []
      for (let z in tablesArr[j].arrs) {
        arrs.push(tablesArr[j].arrs[z].value)
      }
      arr[j].attr = arrs.join(',')
    }
    for (let w in arr) {
      newsArr[arr[w].attr] = arr[w]
    }
    this.setData({
      tablesArr: newsArr
    })
  },
  createShareImage() {
    var that = this;
    if (that.data.qrCodeBase64) {
      that.setData({
        isCanDraw: !that.data.isCanDraw
      })
    } else {
      wx.showLoading({
        title: '获取小程序码'
      })


      wx.request({
        url: `${app.globalData.host}${getUnlimited}`,
        method: 'POST',
        data: {
          "scene": 'id=' + that.data.proId + '&code=' + wx.getStorageSync('code'),
          "page": "pages/detail/detail",
          "width": 1200,
          "auto_color": true,
          "line_color": {},
          "is_hyaline": false
        },
        success(res) {
          var base64 = 'data:image/jpeg;base64,' + res.data.Msg;

          base64src(base64, src => {
            wx.hideLoading()

            that.setData({
              qrCodeBase64: src,
              isCanDraw: !that.data.isCanDraw
            })

          });

        }
      })
    }





  },
  getWeather() {
    var that = this;
    // 新建百度地图对象 
    var BMap = new bmap.BMapWX({
      ak: 'j82U67WeeAacPiCChSOLZBUrdVykVDOg'
    });
    var fail = function(data) {
    };
    var success = function(data) {
      var originalData = data.originalData.results[0];
      var city = originalData.currentCity.replace(/市$/gm, "");
      var dayPictureUrl = originalData.weather_data[1].dayPictureUrl.replace(/http:\/\//gm, "https://");
      that.setData({
        currentCity: city,
        dayPictureUrl: dayPictureUrl
      });
    }
    // 发起weather请求 
    BMap.weather({
      fail: fail,
      success: success
    });
  }

})